/**
 * 声音管理类
 */
cc.Class({
    extends: cc.Component,

    properties: {
        bgmVolume: 1.0,
        bgmAudioID: -1,
        _curBgmUrl: "bgm",
        _AudioClips: [],
    },

    init: function (bgm) {
        var self = this;
        self._AudioClips[self._curBgmUrl] = bgm;
        this.resetLocalAudio();
    },

    resetLocalAudio: function () {
        var t = cc.sys.localStorage.getItem("bgmVolume");

        // console.log("当前背景的缓存值", t);
        if (t === "" || t == null || t == undefined) {
            this.bgmVolume = parseFloat(1);
            this.setBGMVolume(1);
        } else {
            this.bgmVolume = parseFloat(t);
            this.setBGMVolume(this.bgmVolume);
        }
    },

    setBGMVolume: function (v) {
        var self = this;

        if (this.bgmAudioID >= 0) {
            if (v > 0) {
                cc.audioEngine.resume(this.bgmAudioID);
            } else {
                cc.audioEngine.pause(this.bgmAudioID);
            }
        } else {
            if (this._curBgmUrl && v > 0) {
                this.bgmAudioID = cc.audioEngine.play(self._AudioClips[self._curBgmUrl], true, self.bgmVolume);
            }
        }

        // if (this.bgmVolume != v) {
        cc.sys.localStorage.setItem("bgmVolume", v);
        this.bgmVolume = v;
        cc.audioEngine.setVolume(self.bgmAudioID, v);
        // }
    },

    getBgmVolume: function () {
        return this.bgmVolume;
    },

    pauseAll: function () {
        cc.audioEngine.pauseAll();
    },

    resumeAll: function () {
        cc.audioEngine.resumeAll();
    },

    playBGM() {
        var self = this;
        if (this.bgmAudioID >= 0) {
            cc.audioEngine.stop(this.bgmAudioID);
        }
        if (this.bgmVolume > 0) {  //当静音关闭游戏时，重新进入时不会加载声音文件
            self.bgmAudioID = cc.audioEngine.play(self._AudioClips[self._curBgmUrl], true, self.bgmVolume);
        }
    },

    playSFX(name) {
        var self = this;
        if (this.bgmVolume > 0) {
            var audioUrl = "sounds/" + name;

            if (this._AudioClips[name] == undefined) {
                cc.loader.loadRes(audioUrl, cc.AudioClip, function (err, clip) {
                    cc.audioEngine.play(clip, false, self.bgmVolume);
                    self._AudioClips[name] = clip;
                });
            } else {
                cc.audioEngine.play(self._AudioClips[name], false, self.bgmVolume);
            }
        }
    },

    onShow() {
        cc.audioEngine.resumeAll();                //回到游戏时声音恢复
        var getBgm = cc.sys.localStorage.getItem("bgmVolume");
    },
    onHide() {
        cc.audioEngine.pauseAll();
    }

});